import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getBasicConfig, updateBasicConfig } from '@/api/system'

// 系统配置管理
export const useSystemStore = defineStore('system', () => {
  // 系统配置状态
  const systemConfig = ref({
    frontendName: '',  // 前台名称
    backendName: '',   // 后台名称
    logo: '',
    favicon: '',
    loginBackground: '',
    loginLogo: '',
    welcomeText: '',
    footer: ''
  })

  // 获取当前系统名称
  const getSystemName = () => {
    const isAdminRoute = window.location.pathname.startsWith('/admin')
    return isAdminRoute 
      ? (systemConfig.value.backendName?.trim() || '证书管理系统')
      : (systemConfig.value.frontendName?.trim() || '证书查询系统')
  }

  // 更新系统UI
  const updateSystemUI = () => {
    // 更新浏览器标题
    document.title = getSystemName()

    // 更新favicon
    if (systemConfig.value.favicon) {
      let link = document.querySelector("link[rel~='icon']")
      if (!link) {
        link = document.createElement('link')
        link.rel = 'icon'
        document.head.appendChild(link)
      }
      link.href = `${systemConfig.value.favicon}?v=${Date.now()}`
    }

    // 更新系统Logo
    if (systemConfig.value.logo) {
      window.dispatchEvent(new CustomEvent('system-logo-updated', { 
        detail: `${systemConfig.value.logo}?v=${Date.now()}` 
      }))
    }

    // 触发系统名称更新事件
    window.dispatchEvent(new CustomEvent('frontend-name-updated', { 
      detail: systemConfig.value.frontendName 
    }))
    window.dispatchEvent(new CustomEvent('backend-name-updated', { 
      detail: systemConfig.value.backendName 
    }))
  }

  // 获取系统配置
  const fetchSystemConfig = async () => {
    try {
      const res = await getBasicConfig()
      if (res.code === 0 && res.data) {
        systemConfig.value = {
          ...res.data,
          frontendName: res.data.frontendName?.trim() || '证书查询系统',
          backendName: res.data.backendName?.trim() || '证书管理系统'
        }
        updateSystemUI()
      }
    } catch (error) {
      console.error('获取系统配置失败:', error)
    }
  }

  // 更新系统配置
  const updateConfig = async (config) => {
    try {
      const res = await updateBasicConfig(config)
      if (res.code === 0) {
        systemConfig.value = {
          ...config,
          frontendName: config.frontendName?.trim() || '证书查询系统',
          backendName: config.backendName?.trim() || '证书管理系统'
        }
        updateSystemUI()
        return true
      }
      return false
    } catch (error) {
      console.error('更新系统配置失败:', error)
      return false
    }
  }

  return {
    systemConfig,
    getSystemName,
    fetchSystemConfig,
    updateConfig
  }
}) 